'use strict';

/**
 * 邮件发送服务模块
 * 使用阿里云邮件推送服务
 */

const Core = require('@alicloud/pop-core');

// 获取配置
function getEmailConfig() {
  try {
    // 优先从环境变量读取
    if (process.env.ALIYUN_ACCESS_KEY_ID && process.env.ALIYUN_ACCESS_KEY_SECRET) {
      return {
        accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
        accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET
      };
    }
    
    // 从配置中心读取
    const config = require('uni-config-center')({
      pluginId: 'uni-id'
    }).config();
    
    const emailService = config.service?.email?.aliyun || {};
    
    if (emailService.accessKeyId && emailService.accessKeySecret) {
      return {
        accessKeyId: emailService.accessKeyId,
        accessKeySecret: emailService.accessKeySecret
      };
    }
    
    throw new Error('未配置阿里云邮件推送服务的 AccessKey');
  } catch (error) {
    console.error('[EMAIL-SERVICE] 获取配置失败:', error);
    throw error;
  }
}

// 创建邮件客户端
let client = null;
function getClient() {
  if (!client) {
    const emailConfig = getEmailConfig();
    client = new Core({
      accessKeyId: emailConfig.accessKeyId,
      accessKeySecret: emailConfig.accessKeySecret,
      endpoint: 'https://dm.aliyuncs.com',
      apiVersion: '2015-11-23'
    });
  }
  return client;
}

/**
 * 发送邮箱验证码
 */
async function sendVerifyCode({ to, code, expiresIn, scene, from, subject }) {
  const client = getClient();
  
  const params = {
    "RegionId": "cn-hangzhou",
    "AccountName": from || "noreply@your-domain.com", // 需要在阿里云配置的发信地址
    "ReplyToAddress": "false",
    "AddressType": 1,
    "ToAddress": to,
    "Subject": subject?.replace('验证码', `${scene}验证码`) || `【沙画设备】${scene}验证码`,
    "HtmlBody": generateEmailTemplate(code, expiresIn, scene)
  };

  try {
    const result = await client.request('SingleSendMail', params, { method: 'POST' });
    console.log('[EMAIL-SERVICE] 邮件发送成功:', { to, scene });
    return result;
  } catch (error) {
    console.error('[EMAIL-SERVICE] 邮件发送失败:', error);
    throw error;
  }
}

/**
 * 生成邮件HTML模板
 */
function generateEmailTemplate(code, expiresIn, scene) {
  return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: #f5f7fa; padding: 20px; }
        .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 30px; text-align: center; }
        .header h1 { font-size: 28px; font-weight: 600; margin: 0; }
        .content { padding: 40px 30px; }
        .greeting { font-size: 16px; color: #333; margin-bottom: 20px; }
        .purpose { font-size: 15px; color: #666; margin-bottom: 30px; line-height: 1.6; }
        .code-container { background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%); border-radius: 8px; padding: 30px; text-align: center; margin: 30px 0; }
        .code-label { font-size: 14px; color: #666; margin-bottom: 10px; }
        .code { font-size: 40px; color: #667eea; font-weight: bold; letter-spacing: 10px; font-family: 'Courier New', Consolas, monospace; margin: 10px 0; }
        .tips { background: #fff8e1; border-left: 4px solid #ffc107; padding: 20px; margin-top: 30px; border-radius: 4px; }
        .tips-title { font-size: 15px; color: #333; font-weight: 600; margin-bottom: 12px; }
        .tips ul { list-style: none; padding: 0; }
        .tips li { font-size: 14px; color: #666; line-height: 1.8; padding-left: 20px; position: relative; }
        .tips li:before { content: '•'; position: absolute; left: 0; color: #ffc107; font-weight: bold; }
        .footer { background: #f8f9fa; padding: 30px; text-align: center; color: #999; font-size: 13px; line-height: 1.6; }
        .footer p { margin: 5px 0; }
        @media only screen and (max-width: 600px) {
            .container { margin: 0; border-radius: 0; }
            .header { padding: 30px 20px; }
            .content { padding: 30px 20px; }
            .code { font-size: 32px; letter-spacing: 6px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎨 沙画设备管理系统</h1>
        </div>
        <div class="content">
            <div class="greeting">您好，</div>
            <div class="purpose">
                您正在进行<strong>${scene}</strong>操作。为了确保您的账号安全，请使用以下验证码完成验证：
            </div>
            <div class="code-container">
                <div class="code-label">您的验证码</div>
                <div class="code">${code}</div>
            </div>
            <div class="tips">
                <div class="tips-title">🔔 温馨提示</div>
                <ul>
                    <li>验证码有效期为 <strong>${expiresIn} 分钟</strong>，请尽快完成验证</li>
                    <li>请勿将验证码透露给任何人，包括客服人员</li>
                    <li>如果这不是您本人的操作，请忽略此邮件并检查账号安全</li>
                </ul>
            </div>
        </div>
        <div class="footer">
            <p>此邮件由系统自动发送，请勿直接回复</p>
            <p>&copy; ${new Date().getFullYear()} 沙画设备管理系统 版权所有</p>
        </div>
    </div>
</body>
</html>
  `;
}

module.exports = {
  sendVerifyCode
};
